<template>
  <div class="users">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="users-content">
      <el-card>
        <el-row type="flex" justify="space-between">
          <el-col :span="8">
            <el-input
              class="search"
              @input="changeValue"
              placeholder="请输入需要查询的用户名"
              v-model="searchValue"
              clearable
            ></el-input>
            <el-button class="search" @click="searchUser"
              ><i class="el-icon-search"></i
            ></el-button>
          </el-col>
          <el-button type="primary" @click="addEdit('添加')"
            >添加用户</el-button
          >
        </el-row>

        <el-table :data="tableData" style="width: 100%" stripe border>
          <el-table-column type="index" label="#" width="60"> </el-table-column>
          <el-table-column prop="username" label="用户" width="130">
          </el-table-column>
          <el-table-column prop="role_name" label="角色权限" width="140">
          </el-table-column>
          <el-table-column prop="mobile" label="手机" width="150">
          </el-table-column>

          <el-table-column prop="create_time" label="创建时间" width="120">
            <template v-slot="para">
              <span>{{ para | fil }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="mg_state" label="状态" width="80">
            <template v-slot="bool">
              <el-switch
                v-model="bool.row.mg_state"
                active-color="#13ce66"
                inactive-color="#ff4949"
                @change="changeUserStatus(bool.row)"
              >
              </el-switch>
            </template>
          </el-table-column>

          <el-table-column prop="email" label="邮箱" width="220">
          </el-table-column>
          <el-table-column label="操作" width="220">
            <template v-slot="user">
              <el-button
                size="mini"
                type="primary"
                icon="el-icon-edit"
                @click="addEdit('编辑', user.row)"
              ></el-button>
              <el-button
                size="mini"
                type="danger"
                icon="el-icon-delete"
                @click="removeItem(user.row.id)"
              ></el-button>

              <el-tooltip
                class="item"
                effect="dark"
                content="修改权限"
                placement="top"
                transition
                :enterable="false"
              >
                <el-button
                  size="mini"
                  type="warning"
                  icon="el-icon-setting"
                  @click="allotRights(user.row)"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pagenum"
          :page-size="queryInfo.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-sizes="[2, 5, 10, 50, 100]"
        >
        </el-pagination>
      </el-card>
      <!-- 添加or编辑用户 -->
      <el-dialog
        :title="dialogTitle + '用户'"
        :visible.sync="dialogVisible"
        width="30%"
        :before-close="handleClose"
      >
        <el-form
          :model="ruleForm"
          status-icon
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
        >
          <el-form-item
            label="用户名"
            prop="username"
            :required="dialogTitle != '编辑'"
          >
            <el-input
              v-model="ruleForm.username"
              :disabled="dialogTitle == '编辑'"
            ></el-input>
          </el-form-item>

          <el-form-item
            label="密码"
            prop="password"
            v-if="dialogTitle != '编辑'"
          >
            <el-input
              type="password"
              v-model="ruleForm.password"
              autocomplete="off"
            ></el-input>
          </el-form-item>

          <el-form-item label="手机号码" prop="mobile">
            <el-input v-model="ruleForm.mobile"></el-input>
          </el-form-item>

          <el-form-item label="邮箱" prop="email">
            <el-input v-model="ruleForm.email"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="resetForm('ruleForm')">取 消</el-button>
          <el-button type="primary" @click="submitForm('ruleForm')"
            >确 定</el-button
          >
        </span>
      </el-dialog>
      <!-- 修改权限 -->
      <el-dialog
        title="提示"
        :visible.sync="allotDialogVisible"
        width="30%"
        :before-close="handleClose1"
      >
        <p>当前用户 : {{ allot.username }}</p>
        <p>当前角色 ：{{ allot.role }}</p>
        <el-select v-model="value" placeholder="请选择">
          <el-option
            v-for="item in options"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          >
          </el-option>
        </el-select>
        <span slot="footer" class="dialog-footer">
          <el-button @click="allotDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveSelect">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
export default {
  name: 'users',

  data() {
    var checkPass = (rule, value, callback) => {
      if (value.length > 14 || value.length < 6) {
        callback('请输入6-14位密码')
      } else {
        callback()
      }
    }
    var checkMobile = (rule, value, callback) => {
      const reg =
        /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
      if (!reg.test(value)) {
        callback(new Error('号码验证失败'))
      } else {
        callback()
      }
    }

    var checkEmail = (rule, value, callback) => {
      const reg = /^\w+([-+.]?\w+)@\w+([-.]\w+).\w+([-.]\w+)*$/

      if (!reg.test(value)) {
        callback(new Error('号码验证失败'))
      } else {
        callback()
      }
    }
    return {
      tableData: [], //数组数组
      searchValue: '', //绑定搜索框
      total: 0, //总条数
      queryInfo: {
        pagenum: 1, //第几页
        pagesize: 10, //每页多少
      },
      dialogVisible: false, //是否显示弹出层
      dialogTitle: '添加用户',
      tempId: 0, //临时id存储
      allotDialogVisible: false,
      ruleForm: {
        username: '',
        password: '',
        mobile: '',
        email: '',
      },
      allot: {
        //分配角色
        username: '',
        role: '',
      },
      options: [], //分配角色数据
      value: '', //分配角色选中项
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur',
          },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { validator: checkPass, trigger: 'blur' },
        ],
        mobile: [{ validator: checkMobile, trigger: 'blur' }],
        email: [{ validator: checkEmail, trigger: 'blur' }],
      },
    }
  },
  created() {
    this.getUserInfo()
  },
  filters: {
    fil(val) {
      //处理时间
      return new Date(val.row.create_time).toLocaleDateString()
    },
  },
  methods: {
    getUserInfo() {
      this.$axios
        .get('/api/users', { params: this.queryInfo })
        .then(({ data, meta }) => {
          // console.log(data);
          if (meta.status === 200) {
            this.total = data.total
            this.tableData = data.users
          }
        })
    },
    searchUser() {
      //搜索
      this.tableData = this.tableData.filter((item) => {
        return item.username.indexOf(this.searchValue) != -1
      })
    },
    changeValue() {
      if (!this.searchValue) {
        this.getUserInfo()
      } else {
        this.searchUser()
      }
    },
    addEdit(val, info) {
      //添加  or   编辑
      this.dialogTitle = val
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.ruleForm.resetFields()
        if (this.dialogTitle == '编辑') {
          const obj = Object.create(info)
          this.tempId = info.id
          for (let prop in this.ruleForm) {
            this.ruleForm[prop] = obj[prop]
          }
        }
      })
    },
    async submitForm(formName) {
      //提交

      let submitStatus = (status, text) => {
        if (status == 200 || status == 201) {
          this.$message.success(text + '成功')
          this.dialogVisible = false
          this.getUserInfo()
        } else {
          this.$message.error(text + '失败')
        }
      }

      //
      if (this.dialogTitle != '编辑') {
        this.$refs[formName].validate(async (valid) => {
          if (valid) {
            const { meta } = await this.$axios.post('/api/users', this.ruleForm)
            console.log(meta)
            submitStatus(meta.status, '添加')
          }
        })
      } else if (this.dialogTitle == '编辑') {
        this.$refs[formName].validate(async (valid) => {
          if (valid) {
            const { mobile, email } = this.ruleForm
            const { meta } = await this.$axios.put(
              '/api/users/' + this.tempId,
              {
                mobile,
                email,
              }
            )
            console.log(meta)
            submitStatus(meta.status, '编辑')
          }
        })
      }
    },
    resetForm(formName) {
      //重置
      this.dialogVisible = false
      this.$refs[formName].resetFields()
    },

    removeItem(id) {
      this.$confirm('是否确认删除？', '确认信息', {
        distinguishCancelAndClose: true,
        confirmButtonText: '确认',
        cancelButtonText: '取消',
      })
        .then(async () => {
          const { meta } = await this.$axios.delete('/api/users/' + id)

          if (meta.status == 200) {
            this.$message.success('删除成功')
            this.getUserInfo()
          } else {
            this.$message.error('删除失败')
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '取消删除',
          })
        })
    },

    handleSizeChange(val) {
      //改变每页条数
      this.queryInfo.pagesize = val
      this.getUserInfo()
    },
    handleCurrentChange(val) {
      //当前第几页
      this.queryInfo.pagenum = val
      this.getUserInfo()
    },
    handleClose(done) {
      let tempFlag = true //任意一项有值，都不能直接关闭
      for (let prop in this.ruleForm) {
        if (this.ruleForm[prop]) {
          tempFlag = false
        }
      }

      if (tempFlag) {
        done()
        this.tempId = null
        this.dialogTitle = null
      } else {
        this.$confirm('确认关闭？')
          .then(() => {
            done()
            this.tempId = null
            this.dialogTitle = null
          })
          .catch(() => {})
      }
    },
    async allotRights(val) {
      //分配角色权限
      this.allotDialogVisible = true
      this.allot.username = val.username
      this.allot.role = val.role_name
      this.allot.id = val.id
      this.value = ''
      const { data, meta } = await this.$axios.get(`/api/roles`)
      if (meta.status == 200) {
        this.options = data

        // console.log(data);
      }
    },
    async saveSelect() {
      //保存分配角色
      if (!this.value) {
        return this.$message.error('请选择需要分配的角色')
      }
      const { meta } = await this.$axios.put(
        `/api/users/${this.allot.id}/role`,
        { rid: this.value }
      )

      if (meta.status == 200) {
        this.$message.success('保存成功')
        this.getUserInfo()
        this.allotDialogVisible = false
        
      }else{
        this.$message.error(meta.msg)
      }
    },
    handleClose1(done) {
      if (!this.value) {
        done()
      } else {
        this.$confirm('确认关闭？')
          .then(() => {
            done()
          })
          .catch(() => {})
      }
    },
    async changeUserStatus(val) {
      const { meta } = await this.$axios.put(
        `/api/users/${val.id}/state/${val.mg_state}`
      )
      if (meta.status == 200) {
        this.$message.success('修改状态成功')
      } else {
        this.$message.error('修改状态失败')
      }
      // val=data
    },
  },
}
</script>

<style lang="less" scoped>
@import './users.less';
</style>
